package com.atguigu.hellomp;

import com.atguigu.hellomp.entity.User;
import com.atguigu.hellomp.mapper.UserMapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

/**
 * @BelongsProject: lease
 * @BelongsPackage: com.atguigu.hellomp
 * @Author: jiangyi
 * @CreateTime: 2025-08-13  21:56
 * @Description: TODO
 * @Version: 1.0
 */
@SpringBootTest
public class test02 {
    @Autowired
    private UserMapper userMapper;


    @Test
    public void test01() {
        // 测试乐观锁成功状态
        User user = userMapper.selectById(9);
        user.setName("苦海崖");
        user.setAge(100);
        userMapper.updateById(user);
    }

    @Test
    public void testDelete() {
        int i = userMapper.deleteByMap(new HashMap<String, Object>() {
            {
                put("name", "扫地哥");
            }
        });
        System.out.println(i);
    }

    @Test
    public void testSelect() {
        List<User> users = userMapper.selectByMap(new HashMap<String, Object>() {
            {
                put("name", "扫地哥");
            }
        });
        System.out.println(users);
    }

    /**
     * 乐观锁--不主动加锁，出现冲突之后检查version值，如果版本号不一致则更新失败
     * 悲观锁--主动加锁。
     */
    @Test
    public void test02() {

        // 模拟测试乐观锁失败状态
        User user1 = userMapper.selectById(9L);
        user1.setName("法海");
        user1.setAge(100);
        // 此时插队线程执行
        User user2 = userMapper.selectById(9L);
        user2.setName("插队");
        user2.setAge(99);
        userMapper.updateById(user2);
        // 没有乐观锁则会覆盖掉user2
        userMapper.insert(user1);
    }

    // 条件查询 map
    @Test
    public void testSelectByMap() {
        HashMap<String, Object> map = new HashMap<>();
//        map.put("name", "Jack");
        map.put("age", 99);

        List<User> users = userMapper.selectByMap(map);
        users.forEach(System.out::println);

    }

    // 测试分页插件
    @Test
    public void testPage() {
        Page<User> page = new Page<>(1, 5);
        userMapper.selectPage(page, null);
        page.getRecords().forEach(System.out::println);
    }

    // 批量查询数据
    @Test
    public void test03() {
        List<User> list = userMapper.selectBatchIds(Arrays.asList(1, 2, 3));
        //list.forEach(System.out::println);
        list.forEach(x -> System.out.println(x));
    }
}
